﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using System.Collections.ObjectModel;
using System.Collections;

namespace TV_Organizer
{
    /// <summary>
    /// Interaction logic for ListEditionWindow.xaml
    /// </summary>
    public partial class StringListEditionWindow : MetroWindow
    {
        private IList _list;

        public StringListEditionWindow(IList list)
        {
            this.DataContext = this;

            _list = list;
            this.List = new ObservableCollection<string>(list.OfType<string>());

            InitializeComponent();
        }

        public static readonly DependencyProperty ListProperty = DependencyProperty.Register("List", typeof(ObservableCollection<string>), typeof(StringListEditionWindow));
        public ObservableCollection<string> List
        {
            get { return (ObservableCollection<string>)GetValue(ListProperty); }
            set { SetValue(ListProperty, value); }
        }

        protected override void OnClosed(EventArgs e)
        {
            if (this.DialogResult.HasValue && this.DialogResult.Value)
            {
                // Remove deleted values
                foreach (var item in _list.OfType<string>().ToList())
                {
                    if (!this.List.Contains(item))
                        _list.Remove(item);
                }

                // Add added values --> Keep index
                for (int i = 0; i < this.List.Count; i++)
                {
                    var item = this.List[i];
                    if (!_list.Contains(item))
                        _list.Insert(i, item);
                }
            }

            base.OnClosed(e);
        }

        private void AddValueButton_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void DeleteValueButton_Click(object sender, RoutedEventArgs e)
        {
            var value = sender.GetDataContext<string>();
            if (!string.IsNullOrEmpty(value))
                this.List.Remove(value);
        }

        private void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }
    }
}
